using System;
using System.Collections.Generic;

using DevExpress.ExpressApp;
using System.Reflection;
using DevExpress.ExpressApp.DC;
using DevExpress.ExpressApp.Model;
using DevExpress.Xpo;
using DevExpress.ExpressApp.Editors;


namespace SCMSolution.Module
{
    public sealed partial class SCMSolutionModule : ModuleBase
    {
        public SCMSolutionModule()
        {
            InitializeComponent();
        }
        public override void Setup(XafApplication application)
        {
            base.Setup(application);
            application.CustomProcessShortcut += new EventHandler<CustomProcessShortcutEventArgs>(application_CustomProcessShortcut);
        }

        void application_CustomProcessShortcut(object sender, CustomProcessShortcutEventArgs e)
        {
            if (e.Shortcut != null && !string.IsNullOrEmpty(e.Shortcut.ViewId))
            {
                IModelView modelView = Application.FindModelView(e.Shortcut.ViewId);
                if (modelView != null)
                {
                    ITypeInfo typeInfo = modelView.ModelClass.TypeInfo;
                    AutoCreatableObjectAttribute attribute = typeInfo.FindAttribute<AutoCreatableObjectAttribute>(true);
                    if (attribute != null && attribute.AutoCreatable)
                    {
                        ObjectSpace objSpace = Application.CreateObjectSpace();
                        object obj;
                        if (typeof(XPBaseObject).IsAssignableFrom(typeInfo.Type))
                        {
                            obj = objSpace.FindObject(typeInfo.Type, null);
                            if (obj == null)
                            {
                                obj = objSpace.CreateObject(typeInfo.Type);
                            }
                        }
                        else
                        {
                            if (typeInfo.Type == typeof(WelcomeObject))
                            {
                                obj = WelcomeObject.Instance;
                            }
                            else
                            {
                                obj = Activator.CreateInstance(typeInfo.Type);
                            }
                        }
                        //obj = typeof(BaseObject).IsAssignableFrom(typeInfo.Type) ? objSpace.CreateObject(typeInfo.Type) : Activator.CreateInstance(typeInfo.Type);
                        DetailView detailView = Application.CreateDetailView(objSpace, obj, true);
                        if (attribute.ViewEditMode == ViewEditMode.Edit)
                        {
                            detailView.ViewEditMode = DevExpress.ExpressApp.Editors.ViewEditMode.Edit;
                        }
                        e.View = detailView;
                        e.Handled = true;
                    }
                }
            }
        }
    }
}
